import * as types from './actionTypes';
import * as appActions from '../app/actions';
import { setFetching } from '../common/actions';

import Request from '../../utils/request.js';
import { forwardTo } from '../../utils/index';
import md5 from 'md5';
import API from '../../../../config/api';
import reqwest from 'reqwest';

import { message } from 'antd';
export function onChangeInput(key,value){
    return { type:types.ON_CHANGE_INPUT, key, value }
}

export function doLogin(router){
    return (dispatch,getState)=>{
        let { email, password, verifyCode } = getState().auth;

        if(email.length < 3){
            return message.error("帐户名不合法!");
        }
        if(password.length < 6){
            return message.error("密码不能少于6位!");
        }
        //if(!verifyCode){
        //    return alert("验证码不能为空!");
        //}
        password = password;
        dispatch( setFetching( "USER_LOGIN_FETCHING",true ) );
        reqwest(Request.getOptions(
            "post",
            API.auth,
            {
                account:email,password,verifyCode
            }
        )).then( response => {
            Request.setSession(response.token);
            dispatch(appActions.loginSucess());
            router.push("/home");
        }).fail(function (err) {
            Request.handleError(err);
        }).always((resp) =>{
            dispatch( setFetching( "USER_LOGIN_FETCHING",false ) );
        });

    }
}

export function delLogAs() {
    return (dispatch)=>{
        reqwest(Request.getOptions(
            "delete",
            API.logas,
            null,
            true
        )).then( response => {
            Request.setSession(response.token);
            window.location.reload();
        }).fail(function (err) {
            Request.handleError(err);
        }).always((resp) =>{});
    }
}
export function logAs(id) {
    return ()=>{
        reqwest(Request.getOptions(
            "put",
            API.logas+"/"+id,
            {id},
            true
        )).then( response => {
            Request.setSession(response.token);
            window.location.reload();
        }).fail(function (err) {
            Request.handleError(err);
        }).always((resp) =>{});
    }
}
